package com.apes.hr.base.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.api.DomainService;

import com.apes.hr.base.model.WorkPost;
import com.apes.hr.base.model.WorkPostGroup;
import com.apes.hr.base.repository.WorkPostGroupRepository;
import com.apes.hr.base.repository.WorkPostRepository;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


/**
 * 功能：岗位
 *
 * @author HuJianLin
 * @create 2018-04-28 14:35
 */
@Service("hrWorkPostService")
public class WorkPostService extends DomainService {
    @Autowired
    public WorkPostRepository workPostRepository;

    @Autowired
    public WorkPostGroupRepository workPostGroupRepository;


    public WorkPost save(SimpleRequest request) {
        WorkPost workPost = request.getO(WorkPost.class);
        WorkPost byName = workPostRepository.findByName(workPost.getName());
        if(byName != null) throw new RuntimeException("岗位名称重复，请重新填写");
        return workPostRepository.saveAndFlush(workPost);
    }

    public JSONObject findValid(SimpleRequest request){
        JSONObject conditionsJo = request.getJO();
        JSONArray conditions = conditionsJo.getJSONArray("condition");
        if(conditions == null) return conditionsJo;
        conditions.forEach(condition ->{
            JSONObject conditionJo = (JSONObject) condition;
            if("valid".equals(conditionJo.getString("field"))){
                if (conditionJo.getString("value").equals("0")) {
                    conditionJo.put("value",0);
                }
            }
        });
        conditionsJo.put("condition",conditions);
        return conditionsJo;
    }

    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<WorkPost> find(SimpleRequest request) {
        return workPostRepository.find( request.get("key"), PageRequest.of(request.get("page"), request.get("size")) );
    }
    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<WorkPostGroup> findGroup(SimpleRequest request) {
        return workPostGroupRepository.find( request.get("key"), PageRequest.of(request.get("page"), request.get("size")) );
    }


    public Page<WorkPost> findAll(SimpleRequest request) throws Exception {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return workPostRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    public WorkPost findOne(String id) {
        return workPostRepository.findOne(id);
    }
}
